<?php

namespace app\manage\controller;
use app\model\Company;
use app\model\Role;
use app\model\Admin;
use think\Db;

class System extends Base
{
    /**
     * Undocumented 角色列表
     *
     * @param Request $request
     * @return void
     */
    public function role(){

        $this->assign("role",Role::select());
        
        return view("role");
    }

    /**
     * 公司列表
     * @param Request $request
     * @return void
     */
    public function companyList(){

        $this->assign("company",Company::select());
        return view("company");
    }



    /**
     * Undocumented 编辑权限
     *
     * @param Request $request
     * @return void
     */
    public function role_details(){
        if($this->request->isAjax()){
            $data = $this->request->param('action');
            $result = Role::where("id",$this->request->param("role_id"))->update(['action'=>$data]);
            if($result){
                get_list_insert('role',Role::select());
                $redis = new \Predis\Client();
                $redis->set('menu',json_encode(Db::name("menu")->select()));//
                $this->success('操作成功','/manage/role');
            }else{
                $this->error("操作失败");
            } 
        }
        $role_id = $this->request->param("id");
        $info = Role::where("id",$role_id)->find();
        $data['id'] =$info->id;
        $data['action'] = explode(",",$info->action);
        $this->assign("data",$data);
        if($role_id == '6' || $role_id == '7'){
            $this->assign("list",getTree(Db::name("menu")->where('status',2)->select()));
        }else{
            $this->assign("list",getTree(Db::name("menu")->where('status',1)->select()));
        }
        
        return view("update_role");
    }
    /**
     * Undocumented 菜单
     *
     * @return void
     */
    public function menu(){

        $menu = Db::name("menu")->where('status',1)->select();
        $list = $this->getMenu($menu);
        $this->assign("list",$list);
        $this->assign("mch_list",$this->getMenu(Db::name("menu")->where('status',2)->select()));
        $this->assign("tree",make_option_tree_for_select($menu));
        $this->assign("mch_tree",make_option_tree_for_select($this->getMenu(Db::name("menu")->where('status',2)->select())));
        return view("menu");
    }
    /**
     * Undocumented 编辑菜单
     *
     * @return void
     */
    public function menuEdit(){
        if($this->request->isPost()){
            $data = $this->request->param();
            unset($data['admin_auth']);
            unset($data['role_id']);
            $id = $data['id'];
            unset($data['id']);
            $result = Db::name("menu")->where("id",$id)->update(array_filter($data));
            if(!$result){
                return $this->success('修改失败');
            }
            return $this->success('修改成功');
        }
        $info = Db::name("menu")->where("id",$this->request->param('id'))->find();
        if(empty($info)){
            return $this->error("数据不存在");
        }
        if($info['status'] == 1){//后台菜单
            $this->assign("menutree",make_option_tree_for_select($this->getMenu(Db::name("menu")->where('status',1)->select()),0,$info['id']));
        }else{//商户菜单
            $this->assign("menutree",make_option_tree_for_select($this->getMenu(Db::name("menu")->where('status',2)->select()),0,$info['id']));
        }
        $this->assign("info",$info);
        return view("menuEdit");
    } 
    public function addMenu(){
        $data = $this->request->param();
      
        unset($data['admin_auth']);
        Db::startTrans();
        try {
            Db::name("menu")->insert(array_filter($data));
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }
        // $client = new \Predis\Client();
        // $client->set("menu",json_encode(Db::name("menu")->select()));
        return $this->success("添加成功");
    }
    /**
     * Undocumented 菜单排序
     *
     * @return void
     */
    public function menuSort(){
      
        $info = Db::name("menu")->where("id",$this->request->param('id'))->find();
        if(!$info){
            return $this->error("数据不存在");
        }
        Db::startTrans();
        try {
            Db::name("menu")->where("id",$info['id'])->update(array("sort"=>$this->request->param('sort')));
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }
        // $client = new \Predis\Client();
        // $client->set("menu",json_encode(Db::name("menu")->select()));
        $this->success('操作成功');
    }
    /**
     * Undocumented 菜单状态
     *
     * @return void
     */
    public function menuType(){
        $id = $this->request->param('mid');
        $info = Db::name("menu")->where("id",$id)->find();
        if(!$info){
            return $this->error("数据不存在");
        }
        $type = $info['type']==2 ? '1' : '2';
        Db::startTrans();
        try {
            Db::name("menu")->where("id",$info['id'])->update(array("type"=>$type));
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }
        // $client = new \Predis\Client();
        // $client->set("menu",json_encode(Db::name("menu")->select()));
        $this->success('操作成功');
    }
    /**
     * Undocumented 删除菜单
     *
     * @return void
     */
    public function meunDel(){
        $id = $this->request->param('id');
        $info = Db::name("menu")->where("id",$id)->find();
        if(!$info){
            return $this->error("数据不存在");
        }
        if(Db::name("menu")->where("pid",$id)->find()){
            return $this->error("请先删除下级");
        }
        Db::startTrans();
        try {
            Db::name("menu")->where("id",$info['id'])->delete();
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }
        // $client = new \Predis\Client();
        // $client->set("menu",json_encode(Db::name("menu")->select()));
        return $this->success('操作成功');
    }
    /**
     * Undocumented 后台管理账号
     *
     * @return void
     */
    public function system_account(){
        $name = input('name');
        $list = Admin::alias('a')->where(function($query){
            $name = input('name');
            if(!empty($name)){
                $query->where('nickname','like','%'.$name.'%');
            }
        })
        ->join('role b','a.role_id = b.id')
        ->join('company c','a.cid = c.id')
        ->field('a.id,a.user_name,a.nickname,c.company_name,a.role_id,a.type,a.create_time,b.role_name,b.level')
        ->order('create_time', 'desc')->paginate(20,false,['query' =>$this->request->param()]);
        $page = $list->render();
        $this->assign("page",$page);
        $this->assign("list",$list);
        return view('account');
    }
    /**
     * Undocumented 修改密码
     *
     * @return void
     */
    public function up_pwd(){
        $old_pwd = $this->request->param("old_pwd",'','strip_tags,trim');
        $new_pwd = $this->request->param("new_pwd",'','strip_tags,trim');
        $pwd = $this->request->param("pwd",'','strip_tags,trim');
        if($new_pwd == $old_pwd){
            return $this->error("新密码不能和旧密码相同");
        }
        if($new_pwd != $pwd){
            return $this->error("确认密码和新密码不一致");
        }
        $admin_auth = Session("auth_admin");
        if(!$admin_auth){
            return $this->error("登录超时",'/manage/login');
        }
        $info = Admin::where("id",$admin_auth['auth_admin_id'])->find();
        $Aes = new \Aes();
        $o_pwd = $Aes->decrypt($info->password);//解密
        if($o_pwd != $old_pwd){
            return $this->error("旧密码输入错误");
        }
        $info->password = $Aes->encrypt($new_pwd);
        $info->save();
        return $this->success("修改成功");
    }
    /**
     * Undocumented 获取公司列表，职务列表
     *
     * @return void
     */
    public function ajax_select(){
        $info = array();
        $id = $this->request->param('id');
        if(empty($id)){
            $company = Company::getCompany();
            $role =  Role::selectRole(1);
        }else{
            $info = Admin::where("id",$id)->field("id,user_name,role_id,nickname,cid")->find();
            $company = Company::getCompany($info->cid);
            $role = Role::selectRole($info->cid,$info->role_id);
        }
        return [ 'info'=>$info,'select'=>$role,'company'=> $company];
    }

    /**
     * 根据公司id获取职位
     * @return void
     */
    public function getPosition(){
        $cid = $this->request->param('cid');
        $position =  Role::selectRole($cid);
        return ['position'=>$position];
    }

   /**
     * 获取公司列表
     * @return void
     */
    public function getCompany(){
        $info = array();
        $id = $this->request->param('id');
        if($id == 0){
            $company = Company::getCompany();
            $level = Role::getLevel();
            $role_name = "";
        }else{
            $info = Role::where("id",$id)->find();
            $company = Company::getCompany($info->c_id);
            $level = Role::getLevel($info->level);
            $role_name = $info->role_name;

        }
       
        return ['company'=>$company,'level'=>$level,'role_name'=>$role_name];
    }

   /**
     * 公司详情
     * @param Request $request
     * @return void
     */
    public function companyDetail(){
        $id = $this->request->param("id");
        if($id){
            $info = Company::where("id",$id)->find();
            $company_name = $info->company_name;
        }else{
            $company_name = '';
        }
        return ['company_name'=>$company_name,'id'=>$id];
    }

    /**
     * 添加/修改公司
     * @return void
     */
    public function editCompany(){ 
        $data = $this->request->param();
        $result = Company::editCompany($data);
        if($result === true){            
            return $this->success("操作成功");
        }else{
            return $this->error($result);
        }
    }
    /**
     * Undocumented 添加/编辑账号
     *
     * @return void
     */
    public function save_account(){ 
        $data = $this->request->param();
        $result = Admin::adminAdd($data);
        if($result === true){
            /*if(!empty($data['id'])){//更新
                if($data['role_id'] == 2){
                    getLog($this->request->admin_auth['auth_admin_id'],$this->request->admin_auth['role_id'],'更新代理商账号ID['.$data['role_id'].']信息');
                }else{
                    getLog($this->request->admin_auth['auth_admin_id'],$this->request->admin_auth['role_id'],'更新其他角色账号ID['.$data['role_id'].']信息');
                }
            }else{
                $txt = '创建账号：['.$data['name'].']';
                getLog($this->request->admin_auth['auth_admin_id'],$this->request->admin_auth['role_id'],$txt);
            }*/
            
            return $this->success("操作成功");
        }else{
            return $this->error($result);
        }
    }
   /**
     * 添加/修改职务
     * @return void
     */
    public function editPosition(){ 
        $data = $this->request->param();
        $result = Role::editPosition($data);
        if($result === true){            
            return $this->success("操作成功");
        }else{
            return $this->error($result);
        }
    }
    /**
     * Undocumented 更新账号状态
     *
     * @return void
     */
    public function account_status(){
        $id = $this->request->param("mid");
        $info = Admin::where("id",$id)->find();
        if(empty($info)){
            return $this->error("数据不存在");
        }
        $info->type = $info->type == 2 ? 1 : 2;
        $info->save();
        $st = $info->type == 1 ? '开启' : '禁用';
        $txt = '更新['.$info->nickname.']状态为：'.$st;
        getLog($this->request->admin_auth['auth_admin_id'],$this->request->admin_auth['role_id'],$txt);
        return $this->success("操作成功");
    }
    /**
     * Undocumented 删除账号
     *
     * @return void
     */
    public function acc_delete(){
        $id = $this->request->param("id");
        $info = Admin::where("id",$id)->find();
        if(!empty($info)){
            $info->delete();
            return $this->success("操作成功");
        }
        return $this->error("数据不存在");
    }
    /**
     * Undocumented 操作记录
     *
     * @return void
     */
    public function log(){
        $list = Db::name("log")->order("id",'desc')->where(function($query){
            $start = input("start",date('Y-m-d 00:00:00',time()));
            $end = input("end",date('Y-m-d H:i:s',time()));
            if(!empty($start) && !empty($end)){
                $query->where("create_time",'between',[$start,$end]);
            }
        })->paginate(10,false,['query' =>$this->request->param()]);
        $page = $list->render();
        $this->assign("data",$this->request->param());
        $this->assign("list",$list);
        $this->assign("page",$page);
       return view('log'); 
    }
    
}